<?php

namespace Frieza\Modules\Push\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use Doraemon\model\AdmPush\PushType;

class PushTypeController extends Controller
{

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 一级推送类型列表
     * @param Content $content
     * @return Content
     */
    public function list(Content $content)
    {
        $firstList = PushType::selectByWhere([
            'pid' => 0,
            'ORDER' => ['id' => 'ASC']
        ]);
        $ids = $firstList ? array_column($firstList, 'id') : [];
        $secondList = [];
        if ($ids) {
            $secondArr = PushType::selectByWhere([
                'pid' => $ids,
                'data_status' => PushType::STATUS_NORMAL
            ]);
            if ($secondArr){
                foreach ($secondArr as $row) {
                    $secondList[$row['pid']][] = $row;
                }
            }
        }
        $list = [];
        foreach ($firstList as $row) {
            $row['second_list'] = isset($secondList[$row['id']]) ? $secondList[$row['id']] : [];
            $list[] = $row;
        }
        $gridModel = new pGridDataModel($list);
        $categoryGird = Admin::grid($gridModel, function (Grid $grid) {
            $grid->disableExport();
            $grid->disableFilter();
            $grid->disableRowSelector();
            $grid->disableColumnSelector();
            $grid->disablePagination();
            $grid->column('id');
            $grid->column('type_name', '一级类型');
            $grid->column('type_desc', '描述');
            $grid->column('second_list', '二级类型')->display(function () {
                $format = [];
                if ($this->second_list) {
                    foreach ($this->second_list as $row) {
                        $format[] = $row['type_name'];
                    }
                }
                return $format;
            })->label('info');
            $grid->column('type_time', '触发时间')->display(function() {
                return json_decode($this->type_time);
            })->label('default');
            $grid->column('data_status', '数据状态')->display(function () {
                $status = PushType::STATUS_ARR[$this->data_status];
                return $status;
            })->label([
                1 => 'success',
                9 => 'default',
            ]);
            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->disableDelete();
                $actions->disableView();
                //获取一级推送类型的状态,隐藏状态的不显示操作
                $id = $actions->row->id;
                $rank_info = PushType::getByWhere(['id' => $id]);
                if ($rank_info['data_status'] == PushType::STATUS_DELETED){
                    $actions->disableEdit();
                }
            });
        });
        $tab = new Tab();
        $tab->add('一级推送类型', $categoryGird->render(), true);
        $content->row($tab);
        return $content
            ->header('推送类型管理')
            ->description(' ')
            ->breadcrumb(['text' => '推送类型管理']);
    }

    /**
     * 一级类型编辑页
     * @param Content $content
     * @param int $firstId
     * @return Content
     */
    public function firstEdit(Content $content, $firstId = 0)
    {
        $tab = new Tab();
        //基础信息
        $firstInfo = [];
        if ($firstId) {
            $header = "编辑一级类型";
            $firstInfo = PushType::getByWhere(['id' => $firstId]);
            $firstInfo['type_time'] = json_decode($firstInfo['type_time'], true);
        }else{
            $header = "添加一级类型";
        }
        $basicForm = new Form($firstInfo);
        $type_name = $basicForm->text('type_name', '一级类型名')->required()->pattern('^[a-z][0-9a-z]*')->help("请输入小写英文字母和数字, 以字母开头(不支持中文, 不支持数字开头)");
        if($firstId) {
            $type_name->readOnly();
        }
        $basicForm->text('type_desc', '一级类型描述')->required();
        $basicForm->tags('type_time', '触发时间点')->help("请输入10:30这样的时间点，以逗号和空格分隔");
        $basicForm->action('/admin/push/pushType/' . $firstId . '/save');
        $tab->add('基础信息', $basicForm);
        if ($firstId) {
            $secGird = $this->secondGrid($firstId);
            $tab->add('二级类型', $secGird);
        }else{
            $tab->addLink('一级类型列表', url('admin/push/pushType'));
        }
        $content->header($header . ($firstId ? "-" . $firstInfo['type_name'] : ""))
            ->breadcrumb([
                'text' => '推送类型管理',
                'url' => '/push/pushType'
            ], ['text' => '一级类型编辑'])
            ->row($tab);
        return $content;
    }

    /**
     * 保存一级类型信息
     * @param Request $request
     * @param int $firstId
     * @return \Illuminate\Http\RedirectResponse
     */
    public function saveFirst(Request $request, $firstId = 0)
    {
        $data = [];
        $data['type_name'] = trim($request->input('type_name'));
        $data['type_desc'] = trim($request->input('type_desc'));
        $data['type_time'] = array_unique(array_filter($request->input('type_time')));
        $data['deep'] = 1;
        try {
            if ($firstId) {
                $ret = PushType::updateData($data, ['id' => $firstId]);
            } else {
                $ret = PushType::insertData($data);
            }
            if($ret == false) {
                throw new \Exception('保存数据异常');
            }
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }
        $success = new MessageBag([
            'title' => '保存成功'
        ]);
        return redirect('/admin/push/pushType')->with(compact('success'));
    }


    /**
     * 二级类型编辑页
     * @param Content $content
     * @param $firstId
     * @param int $secondId
     * @return Content
     */
    public function childEdit(Request $request, Content $content, $firstId, $secondId = 0)
    {
        $tab = new Tab();
        $secondInfo = [];
        if ($secondId) {
            $secondInfo = PushType::getByWhere(['id' => $secondId]);
        }

        $basicForm = new Form($secondInfo);
        $basicForm->hidden('id');
        $basicForm->hidden('pid')->default($firstId);
        $type_name = $basicForm->text('type_name', '二级类型名')->required()->pattern('^[a-z][0-9a-z]*')->help("请输入小写英文字母和数字, 以字母开头(不支持中文, 不支持数字开头)");
        if($secondId) {
            $type_name->readOnly();
        }
        $basicForm->text('type_desc', '二级类型描述')->required();
        $basicForm->action('/admin/push/pushType/' . $firstId . '/edit/' . $secondId . '/save');
        $content->header('二级类型编辑' . ($secondInfo ? "-" . $secondInfo['type_name'] : ""))
            ->breadcrumb([
                'text' => '类型分类管理',
                'url' => '/push/pushType'
            ], [
                'text' => '一级类型编辑',
                'url' => '/push/pushType/' . $firstId . '/edit'
            ], ['text' => '二级类型编辑']);

        $tab->add('基础信息', $basicForm);
        $content->row($tab);
        return $content;
    }

    /**
     * 保存二级类型
     * @param Request $request
     * @param int $firstId
     * @param int $secondId
     * @return \Illuminate\Http\RedirectResponse
     */
    public function saveSecond(Request $request, $firstId, $secondId = 0)
    {

        $data = [
            'type_name' => trim($request->input('type_name')),
            'type_desc' => trim($request->input('type_desc')),
            'pid' => $firstId,
            'deep' => 2,
        ];
        try {
            if ($secondId) {
                PushType::updateData($data, ['id' => $secondId]);
            } else {
                $info = PushType::getByWhere(['pid' => $firstId, 'type_name' => $data['type_name']]);
                if ($info) {
                    $secondId = $info['id'];
                    $data['data_status'] = PushType::STATUS_NORMAL;
                    PushType::updateData($data, ['id' => $info['id'], 'pid' => $firstId]);
                } else {
                    $first = PushType::getByWhere(['id' => $firstId]);
                    $data['push_id'] = $first['type_name'] . '_' . $data['type_name'];
                    $secondId = PushType::insertData($data);
                }
            }
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }
        $success = new MessageBag([
            'title' => '保存成功'
        ]);
        return redirect('/admin/push/pushType/' . $firstId . '/edit')->with(compact('success'));
    }

    /**
     * 二级类型列表
     * @param $firstId 一级类型id
     * @return string
     */
    private function secondGrid($firstId)
    {
        $list = [];
        $typeList = PushType::selectByWhere([
            'pid' => $firstId,
            'data_status' => PushType::STATUS_NORMAL,
            'ORDER' => ['id' => 'ASC'],
        ]);
        $typeList = $typeList ? array_column($typeList, null, 'id') : [];
        foreach($typeList as $id => $row) {
            $list[] = $row;
        }
        $gridModel = new pGridDataModel($list);
        return Admin::grid($gridModel, function (Grid $grid) use ($firstId) {
            $grid->disableExport();
            $grid->disableFilter();
            $grid->disableRowSelector();
            $grid->disableColumnSelector();
            $grid->disablePagination();
            $grid->column('id');
            $grid->column('type_name', '二级类型名称');
            $grid->column('type_desc', '二级类型描述');
            $grid->column('push_id', 'push_id前缀');
            $grid->column('data_status', '类型展示状态')->display(function () {
                $status = PushType::STATUS_ARR[$this->data_status];
                return $status;
            })->label([
                1 => 'success',
                9 => 'default',
            ]);
            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->disableDelete();
                $actions->disableView();
                //获取一级推送类型的状态,隐藏状态的不显示操作
                $id = $actions->row->id;
                $rank_info = PushType::getByWhere(['id' => $id]);
                if ($rank_info['data_status'] == PushType::STATUS_DELETED){
                    $actions->disableEdit();
                }
            });
        })->render();
    }
}
